import os
import json
import uuid

from django.conf import settings
from django.core.files.storage import default_storage


class FileSystemService:
    def save(self, relative_dir, filename, f):
        absolute_dir = os.path.join(settings.MEDIA_ROOT, relative_dir)
        if not os.path.exists(absolute_dir):
            os.makedirs(absolute_dir)
        with open(f'{absolute_dir}/{filename}', 'wb') as fp:
            fp.write(f)
        file_url = f'{settings.HOST}{settings.MEDIA_URL}{relative_dir}/{filename}'
        return file_url

    def save_dict_content(self, content, relative_dir='', file_name=''):
        ''' 把dict保存到文件中，并返回url
        '''
        json_data = json.dumps(content, indent=4, ensure_ascii=False)
        absolute_dir = os.path.join(settings.MEDIA_ROOT, relative_dir) if relative_dir else settings.MEDIA_ROOT
        if not os.path.exists(absolute_dir):
            os.makedirs(absolute_dir)
        if not file_name:
            file_name = uuid.uuid4().hex
        path = os.path.join(absolute_dir, file_name)
        with default_storage.open(path, 'w') as f:
            f.write(json_data)
        return f'{settings.HOST}{settings.MEDIA_URL}{relative_dir}/{file_name}'


file_system_service = FileSystemService()
